<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: gaozhe <weibo.com/>
// +----------------------------------------------------------------------
namespace watch\open;
use think\Session;
use think\Db;
class Watch
{

    //默认配置
    protected $_config = array(
        'AUTH_ON' => true, // 认证开关
        'AUTH_TYPE' => 1, // 认证方式，1为实时认证；2为登录认证。
        'OPEN_APPID' => '', // 开放平台
        'OPEN_SECRET' => '', // 开放平台
        'AUTH_USER' => 'admin_user', // 用户信息表
    );

    public function __construct()
    {
        $option = [
              'AUTH_USER' => config('database.prefix') . 'admin_user', // 用户信息表
              'AUTH_ON' => true, // 认证开关
              'AUTH_TYPE' => 1, // 认证方式，1为实时认证；2为登录认证。
            ];
        $this->_config = array_merge($this->_config, $option);
    }
    public function https_post($url,$data){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url); 
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, @$data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        if (curl_errno($curl)) {
           return 'Errno'.curl_error($curl);
        }
        curl_close($curl);
        return $result;
    }
    /**
     * 检查用户是否绑定微信
     * @param uid  int           认证用户的id
     * @return boolean           通过验证返回true;失败返回false
     */
    public function check($uid)
    {
        if (!$this->_config['AUTH_ON']) {
            return true;
        }
        $user = Db::table($this->_config['AUTH_USER'])->where(array('id' => $uid))->find();
        if ($user['wx_openid']!="") {
          return true;
        }else{
          return false;
        }
        return false;
    }

    /**
     * 根据用户id 检查access_token是否有效
     * @param  uid int     用户id
     * @return boolean           通过验证返回true;失败返回false
     */
    public function check_access_token($uid)
    {
        $user = Db::table($this->_config['AUTH_USER'])->where(array('id' => $uid))->find();
        if ($user['wx_access_token']!="" && $user['wx_access_token_time_end']>time()) {
          return true;
        }else{
          return false;
        }
        return false;
    }
    /**
     * 根据用户id 检查刷新凭证是否有效
     * @param  uid int     用户id
     * @return boolean           通过验证返回true;失败返回false
     */
    public function check_refresh_token($uid)
    {
        $user = Db::table($this->_config['AUTH_USER'])->where(array('id' => $uid))->find();
        if ($user['wx_access_token']!="" && $user['wx_refresh_token_time_end']>time()) {
          return true;
        }else{
          return false;
        }
        return false;
    }
    /**
     * 刷新access_token有效期
     * @param  uid int     用户id
     * @return string access_token        成功返回微信access_token 失败返回false
     */
    public function get_Refresh_access_token($uid)
    {
      //判断刷新凭证是否有效
      if ($this->check_refresh_token($uid)) {
        $user = Db::table($this->_config['AUTH_USER'])->where(array('id' => $uid))->find();

        $APPID=$this->_config['OPEN_APPID'];
        $refresh_token=$user['wx_refresh_token'];
        $url="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=$APPID&grant_type=refresh_token&refresh_token=$refresh_token";
        $txt = '';
        $result = $this->https_post($url,$txt);
        $unionid_arr = json_decode($result,true);
        if (@$unionid_arr['openid']!="") {
          $access_token=@$unionid_arr['access_token'];//接口调用凭证
          $expires_in=@$unionid_arr['expires_in'];//access_token接口调用凭证超时时间，单位（秒）
          $refresh_token=@$unionid_arr['refresh_token'];//用户刷新access_token
          $openid=@$unionid_arr['openid'];//授权用户唯一标识
          //更新数据
          $data = [
              'wx_access_token' => $access_token,
              'wx_expires_in' => $expires_in,//access_token接口调用凭证超时时间，单位（秒）
              'wx_access_token_time_end' => time()+$expires_in-120,//access_token结束时间
              'wx_refresh_token' => $refresh_token, //用户刷新access_token凭证
              'wx_refresh_token_time' => '30',//refresh_token有效期时间(30天)
              'wx_refresh_token_time_end' => time()+86400*30-120//refresh_token结束时间
          ];
          Db::table($this->_config['AUTH_USER'])->where(array('id' => $uid))->update($data);
          return true;
        }else{
          return false;
        }
      }else{
        return false;
      }
    }
    /**
     * 登录
     */
    public function login($CODE='')
    {
      $APPID=$this->_config['OPEN_APPID'];
      $SECRET=$this->_config['OPEN_SECRET'];
      $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=$APPID&secret=$SECRET&code=$CODE&grant_type=authorization_code";
      $txt = '';
      $result = $this->https_post($url,$txt);
      $unionid_arr = json_decode($result,true);
      return $unionid_arr;

    }

    /**
     * 获得用户资料,根据自己的情况读取数据库
     */
    public function getUserInfo($uid)
    {
      if ($this->check_access_token($uid)) {
        $user = Db::table($this->_config['AUTH_USER'])->where(array('id' => $uid))->find();
        $OPENID=$user['wx_openid'];
        $access_token=$user['wx_access_token'];
        $url="https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$OPENID";
        $txt = '';
        $result = $this->https_post($url,$txt);
        $array = json_decode($result,true);
        // $arr = array();
        // $code='0';
        // $msg='';
        // $arr['username']=$array['nickname'];
        // $arr['sex']=$array['sex'];
        // $arr['language']=$array['language'];
        // $arr['city']=$array['city'];
        // $arr['province']=$array['province'];
        // $arr['country']=$array['country'];
        // $arr['headimgurl']=$array['headimgurl'];
        return $array;
      }
      return false;
    }












}
